package com.isoft.service.impl;

import com.isoft.entity.DfmeGtlsEntity;
import com.isoft.mapper.DfmeGtlsMapper;
import com.isoft.service.DfmeGtlsService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeGtlsServiceImpl implements DfmeGtlsService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeGtlsServiceImpl.class);

    @Autowired
    private DfmeGtlsMapper dfmeGtlsMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-GTLS XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeGtlsEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeGtlsEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeGtlsEntity.class);

            if (entity == null || entity.getDflt() == null || entity.getDflt().getGtls() == null) {
                throw new IllegalArgumentException("Invalid DFME-GTLS XML structure");
            }

            processFlightData(entity);

            return "DFME-GTLS data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-GTLS XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-GTLS XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeGtlsEntity entity) {
        try {
            // 1. 插入元数据
            dfmeGtlsMapper.insertMeta(entity);

            // 2. 插入航班基础信息（如果不存在）
            if (dfmeGtlsMapper.countFlightById(entity.getDflt().getFlightId()) == 0) {
                dfmeGtlsMapper.insertFlightBase(entity);
            }

            // 3. 处理登机口信息
            dfmeGtlsMapper.insertGate(entity);

            // 4. 处理行李转盘信息
            dfmeGtlsMapper.insertBaggageClaim(entity);
        } catch (Exception e) {
            logger.error("处理航班数据失败", e);
            throw new RuntimeException("处理航班数据失败: " + e.getMessage(), e);
        }
    }
}